from frappe.model.naming import getseries,determine_consecutive_week_number,has_custom_parser
from frappe.model import naming

import datetime
from collections.abc import Callable
from typing import TYPE_CHECKING, Optional

import frappe
from frappe import _
from frappe.utils import  cstr, now_datetime

if TYPE_CHECKING:
	from frappe.model.document import Document



# Types that can be using in naming series fields
NAMING_SERIES_PART_TYPES = (
	int,
	str,
	datetime.datetime,
	datetime.date,
	datetime.time,
	datetime.timedelta,
)

def custom_parse_naming_series(
	parts: list[str] | str,
	doctype=None,
	doc: Optional["Document"] = None,
	number_generator: Callable[[str, int], str] | None = None,
) -> str:


	name = ""
	_sentinel = object()
	if isinstance(parts, str):
		parts = parts.split(".")

	if not number_generator:
		number_generator = getseries

	series_set = False
	today = now_datetime()
	for e in parts:
		if not e:
			continue

		part = ""
		if e.startswith("#"):
			if not series_set:
				digits = len(e)
				part = number_generator(name, digits)
				series_set = True
		elif e == "YY":
			part = today.strftime("%y")
		elif e == "MM":
			part = today.strftime("%m")
		elif e == "DD":
			part = today.strftime("%d")
		elif e == "YYYY":
			part = today.strftime("%Y")
		elif e == "WW":
			part = determine_consecutive_week_number(today)
		elif e == "timestamp":
			part = str(today)
#当编号规则中有 dot  则表示 点号 ，满足类似 11.12.1001 这样的物料编码
		elif e=='dot':
			part="."
		elif doc and (e.startswith("{") or doc.get(e, _sentinel) is not _sentinel):
			e = e.replace("{", "").replace("}", "")
			part = doc.get(e)
		elif method := has_custom_parser(e):
			part = frappe.get_attr(method[0])(doc, e)
		else:
			part = e

		if isinstance(part, str):
			name += part
		elif isinstance(part, NAMING_SERIES_PART_TYPES):
			name += cstr(part).strip()

	return name


naming.parse_naming_series=custom_parse_naming_series



# #  重命名客户编号 同步修改到helpdesk 中 hd customer 中
# if 'helpdesk' in frappe.get_installed_apps():
# 	from erpnext.selling.doctype.customer.customer import Customer
# 	origin_after_rename=Customer.after_rename

# 	def custom_after_rename(self, olddn, newdn, merge=False):
# 		origin_after_rename(self, olddn, newdn, merge)

# 		hdcustomer_name=frappe.db.get_value('HD Customer',olddn,'name')
# 		if hdcustomer_name:
# 			frappe.rename_doc('HD Customer',hdcustomer_name,newdn)

# 	Customer.after_rename=custom_after_rename